package com.xbdun.service.bmp.facade;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xbdun.common.api.Client;
import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.qr.LoginMacResponse;
import com.xbdun.common.util.CommonUtil;
import com.xbdun.common.validate.ValidateUtil;
import com.xbdun.facade.bmp.enumx.PlatTypeEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgInvitTypeEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserEducationEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserEffectEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserEnabledEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserInauTypeEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserSexEnum;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.system.LoginCanPagesRequest;
import com.xbdun.facade.bmp.request.system.ModifyOrgUserRequest;
import com.xbdun.facade.bmp.request.system.ModifyUserPowerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPagerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPowerMenuRequest;
import com.xbdun.facade.bmp.request.system.OrgUserRequest;
import com.xbdun.facade.bmp.request.system.QueryOrgUsersRequest;
import com.xbdun.facade.bmp.request.system.UserSpecialPowerRequest;
import com.xbdun.facade.bmp.response.system.QueryOrgUsersResponse;
import com.xbdun.facade.bmp.result.system.OrgUserPagerResult;
import com.xbdun.facade.bmp.result.system.OrgUserPowerMenuResult;
import com.xbdun.facade.bmp.result.system.OrgUserResult;
import com.xbdun.facade.bmp.result.system.QueryOrgUsersPagerResult;
import com.xbdun.facade.bmp.service.system.OrgUserFacade;
import com.xbdun.service.bmp.service.system.OrgUserService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OrgUserFacadeImpl implements OrgUserFacade {

	@Autowired
	OrgUserService orgUserService;
	public XbdUnStringResult addOrgUser(OrgUserRequest request, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 新增机构用户初始参数,{}", request);
			
			CommonUtil.validateClient(client);
			checkedAddOrgUser(request);
			//给新增用户设置默认值
			request.setOrgCode(client.getOrgCode());
			request.setState(UserEffectEnum.EFFECT.getKey());
			orgUserService.addOrgUser(request,client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("新增机构用户失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 新增机构用户结果:{}", result);
		}
		return result;
	}
	
	public XbdUnStringResult addUserDptRolePower(ModifyUserPowerRequest request, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 新增机构用户权限初始参数,{}", request);
			
			CommonUtil.validateClient(client);
			if(StringUtils.isBlank(request.getUserId())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("被设置的用户ID不能为空");
			}
			if(CollectionUtils.isEmpty(request.getRdpIds())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("普通角色权限不能为空");
			}
			//部门编号不能为空作为新增
			if(CollectionUtils.isNotEmpty(request.getRdpIds())&&(null==request.getDepartCode()||request.getDepartCode().longValue()<=0)){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("新增用户关联角色部门编号不合法");
			}
			orgUserService.addUserDptRolePower(request,client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("新增机构用户权限失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 新增机构用户权限结果:{}", result);
		}
		return result;
	}

	public XbdUnStringResult delUserDptRolePower(ModifyUserPowerRequest request, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 删除机构用户权限参数,{}", request);
			
			CommonUtil.validateClient(client);
			if(StringUtils.isBlank(request.getUserId())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("被设置的用户ID不能为空");
			}
			if(CollectionUtils.isEmpty(request.getRdpIds())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("普通角色权限不能为空");
			}
			orgUserService.delUserDptRolePower(request, client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("删除机构用户权限失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 删除机构用户权限结果:{}", result);
		}
		return result;
	}

	public XbdUnStringResult modifyUserSpecialPower(UserSpecialPowerRequest request, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改机构用户特殊权限参数,{}", request);
			
			CommonUtil.validateClient(client);
			if(StringUtils.isBlank(request.getUserId())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("被设置的用户ID不能为空");
			}
			if(CollectionUtils.isEmpty(request.getAddPowers())&&CollectionUtils.isEmpty(request.getDelPowers())){
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("特殊角色新增删除权限不能同时为空");
			}
			orgUserService.modifyUserSpecialPower(request, client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("修改机构用户特殊权限失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 修改机构用户特殊权限结果:{}", result);
		}
		return result;
	}
	
	public OrgUserPagerResult queryOrgUserPager(OrgUserPagerRequest request, Client client) {
		OrgUserPagerResult result = new OrgUserPagerResult();
		try {
			log.info("start - 查询机构下用户入参,{}", request);
			
			CommonUtil.validateClient(client);
			result.setData(orgUserService.queryOrgUserPager(request,client));
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("查询机构下用户失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 查询机构下用户结果:{}", result);
		}
		return result;
	}
	
	public OrgUserPowerMenuResult queryOrgUserPower(OrgUserPowerMenuRequest request, Client client) {
		OrgUserPowerMenuResult result = new OrgUserPowerMenuResult();
		try {
			log.info("start - 查询用户有效的权限 入参,{}", request);
			if(StringUtils.isBlank(request.getUserId())){
				request.setUserId(client.getUserId());
			}
			CommonUtil.validateClient(client);
			result.setData(orgUserService.queryOrgUserPower(request,client));
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("查询用户有效的权限 失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 查询用户有效的权限 结果:{}", result);
		}
		return result;
	}
	
	//检测机构用户信息
	private void checkedAddOrgUser(OrgUserRequest request) {
		StringBuilder sb = new StringBuilder();
		if(StringUtils.isBlank(request.getRealName())){
			sb.append("员工姓名不能为空;");
		}
		if(null==UserSexEnum.getEnum(request.getSex())){
			sb.append("性别格式不正确;");
		}
		if(!ValidateUtil.isIdCard(request.getIdCard())){
			sb.append("身份证号格式不正确;");
		}
		if(!ValidateUtil.isMobile(request.getMobile())){
			sb.append("手机号格式不正确;");
		}
		if(StringUtils.isBlank(request.getJonNum())){
			sb.append("员工工号不能为空;");
		}
		if(!SysOrgInvitTypeEnum.isKey(request.getInvitType())){
			sb.append("邀请方式状态不是系统定义;");
		}
		if(request.getPlatType()>0&&null==PlatTypeEnum.getEnum(request.getPlatType())){
			sb.append("邀请用户的平台类型系统未定义;");
		}
		//员工的角色
		if(!(UserRolesEnums.isAdmin(request.getSpecilRole())||UserRolesEnums.isMember(request.getSpecilRole()))){
			sb.append("企业角色不正确;");
		}
		if(null==UserInauTypeEnum.getEnum(request.getInauType())){
			sb.append("员工就职类型不正确;");
		}
		if(null==UserEducationEnum.getEnum(request.getEducation())){
			sb.append("员工学历系统未定义;");
		}
		if(null==UserEnabledEnum.getEnum(request.getEnabled())){
			sb.append("员工启用状态未定义;");
		}
		if(StringUtils.isNotBlank(request.getOrgEmail())&&!ValidateUtil.isEmail(request.getOrgEmail())){
			sb.append("邮件格式不正确;");
		}
		if (sb.length() > 0) {
			throw BizException.PARAM_CHKE_FAIL.newInstance("%s", sb.toString());
		}
	}

	public OrgUserResult getOrgUserInfo(String userId, Client client) {
		OrgUserResult result = new OrgUserResult();
		try{
			log.info("start - 查询机构用户详情初始参数,{}", client);
			if(StringUtils.isBlank(userId)){
				throw BizException.PARAM_CHKE_FAIL.newInstance("用户ID不能为空!");
			}
			CommonUtil.validateClient(client);
			result.setData(orgUserService.getOrgUserInfo(userId,client));
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("查询机构用户详情失败,入参:{},异常:{}", client, ex);
		} finally {
			log.info("end - 查询机构用户详情结果:{}", result);
		}
		return result;
	}

	public XbdUnStringResult modifyOrgUser(ModifyOrgUserRequest request, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改机构员工初始参数,{}", request);
			
			CommonUtil.validateClient(client);
			checkedModifyOrgUser(request);
			orgUserService.modifyOrgUserById(request,client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("修改机构员工失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 修改机构员工结果:{}", result);
		}
		return result;
	}

	//检测修改机构用户上传参数
	private void checkedModifyOrgUser(ModifyOrgUserRequest request) {
		if (null == request){
			throw BizException.PARAM_CHKE_FAIL.newInstance("请求对象不能为空");
		}
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isBlank(request.getUserId())) {
			sb.append("员工id不能为空");
		}
		if (StringUtils.isNotBlank(request.getMobile())) {
			if (!ValidateUtil.isMobile(request.getMobile())) {
				sb.append("电话格式不正确;");
			}
		}
		if(StringUtils.isNotBlank(request.getJonNum())){
			if (request.getJonNum().length() != 6) {
				sb.append("员工工号长度不合法;");
			}
		}
		if(StringUtils.isNotBlank(request.getOrgEmail())){
			if(!ValidateUtil.isEmail(request.getOrgEmail())){
				sb.append("邮箱格式不正确;");
			}
		}
		if (request.getState() < 0){
			sb.append("生效状态不合法;");
		}
		if (request.getEnabled() < 0) {
			sb.append("启用状态不合法;");
		}
		if (request.getInvitType() < 0) {
			sb.append("邀请方式不合法;");
		}
		if (request.getInauType() < 0) {
			sb.append("员工就职类型不合法;");
		}
		if (request.getSpecilRole() < 0) {
			sb.append("特殊角色不合法;");
		}
		if (sb.length() > 0) {
			throw BizException.PARAM_CHKE_FAIL.newInstance("%s", sb.toString());
		}
	}

	public XbdUnStringResult deleteOrgUser(String userId, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改机构员工初始参数,{}", userId);
			if (StringUtils.isBlank(userId)) {
				throw BizException.PARAM_CHKE_FAIL.newInstance("请求参数不能为空;");
			}
			CommonUtil.validateClient(client);
			orgUserService.deleteOrgUser(userId,client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("修改机构员工失败,入参:{},异常:{}", userId, ex);
		} finally {
			log.info("end - 修改机构员工结果:{}", result);
		}
		return result;
	}
	public QueryOrgUsersPagerResult queryOrgUsersPager(QueryOrgUsersRequest request) {
		QueryOrgUsersPagerResult result = new QueryOrgUsersPagerResult();
		try{
			log.info("start - 查询所属机构下的管理员,{}", request);
			if(null == request.getUserCode() || request.getUserCode().longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("用户编号不能为空!");
			}
			result.setData(orgUserService.queryOrgUsersPager(request));
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("查询所属机构下的管理员失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end - 查询所属机构下的管理员结果:{}", result);
		}
		return result;
	}

	public List<LoginMacResponse> loginCanPages(LoginCanPagesRequest request) {
		List<LoginMacResponse> result = null;
		try{
			log.info("start - 查询所属机构下用户能够登录那几个平台,{}", request);
			if(null ==request.getUserCode() || request.getUserCode().longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("用户编号不能为空!");
			}
			if(null ==request.getOrgCode() || request.getOrgCode().longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("机构编号不能为空!");
			}
			result = orgUserService.loginCanPages(request);
		} catch (Exception ex) {
			log.error("查询所属机构下用户能够登录那几个平台失败,入参:{},异常:{}", request, ex);
		} finally {
			log.info("end -查询所属机构下用户能够登录那几个平台结果:{}", result);
		}
		return result;
	}

	public QueryOrgUsersResponse getUserByOrgUserCode(Long orgCode, Long userCode) {
		QueryOrgUsersResponse result = null;
		try{
			log.info("start - 查询用户机构信息,机构编号["+orgCode+"],用户编号["+userCode+"]");
			if(null == orgCode || orgCode.longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("机构编号不能为空!");
			}
			if(null == userCode || userCode.longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("用户编号不能为空!");
			}
			result = orgUserService.getUserByOrgUserCode(orgCode,userCode);
		} catch (Exception ex) {
			log.error("查询用户机构信息失败,入参:机构编号["+orgCode+"],用户编号["+userCode+"],异常:{}",ex);
		} finally {
			log.info("end - 查询用户机构信息结果,机构编号["+orgCode+"],用户编号["+userCode+"]");
		}
		return result;
	}

	public XbdUnStringResult inviteOrgUser(String userId, int inviteType, Client client) {
		XbdUnStringResult result = new XbdUnStringResult();
		try {
			log.info("start - 修改机构员工邀请方式初始参数,{}{}", userId,inviteType);
			if(StringUtils.isBlank(userId)){
				throw BizException.PARAM_CHKE_FAIL.newInstance("修改邀请方式的员工id不存在");
			}
			if(UserInauTypeEnum.getEnum(inviteType)==null){
				throw BizException.PARAM_CHKE_FAIL.newInstance("修改的邀请方式未定义");
			}
			CommonUtil.validateClient(client);
			orgUserService.inviteOrgUser(userId,inviteType,client);
		} catch (Exception ex) {
			result.setBizException(ex);
			log.error("修改机构员工邀请方式失败,入参:{}{},异常:{}",  userId,inviteType, ex);
		} finally {
			log.info("end - 修改机构员工邀请方式结果:{}", result);
		}
		return result;
	}

	public QueryOrgUsersResponse getUserIsWork(Long orgCode, Long userCode) {
		QueryOrgUsersResponse result = null;
		try{
			log.info("start - 查询用户机构信息,机构编号["+orgCode+"],用户编号["+userCode+"]");
			if(null == orgCode || orgCode.longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("机构编号不能为空!");
			}
			if(null == userCode || userCode.longValue()<=0){
				throw BizException.PARAM_CHKE_FAIL.newInstance("用户编号不能为空!");
			}
			result = orgUserService.getUserIsWork(orgCode,userCode);
		} catch (Exception ex) {
			log.error("查询用户机构信息失败,入参:机构编号["+orgCode+"],用户编号["+userCode+"],异常:{}",ex);
		} finally {
			log.info("end - 查询用户机构信息结果,机构编号["+orgCode+"],用户编号["+userCode+"]");
		}
		return result;
	}
}
